<template>
  <div class="color-panel" :style="[heightContent, widthContent]">
    <el-scrollbar>
    <div class="color-panel-content">
      <!-- 标准颜色 -->
      <div class="standard-colors">
        <h4>标准颜色</h4>
        <div class="color-grid standard-grid">
          <div
            v-for="(color, index) in standardColors"
            :key="`standard-${index}`"
            class="color-item standard-color"
            :style="{ backgroundColor: color }"
            :class="{ active: selectedColor === color }"
            @click="selectColor(color)"
            :title="`标准颜色 ${index + 1}`"
          ></div>
        </div>
      </div>

      <!-- 自定义颜色 -->
      <div class="custom-color">
        <h4>自定义颜色</h4>
        <div class="color-picker-container">
          <div class="color-preview" :style="{ backgroundColor: selectedColor }"></div>
          <div class="color-inputs">
            <div class="input-group">
              <label>R:</label>
              <input
                type="number"
                min="0"
                max="255"
                v-model.number="rgbColor.r"
                @input="updateColorFromRGB"
              />
            </div>
            <div class="input-group">
              <label>G:</label>
              <input
                type="number"
                min="0"
                max="255"
                v-model.number="rgbColor.g"
                @input="updateColorFromRGB"
              />
            </div>
            <div class="input-group">
              <label>B:</label>
              <input
                type="number"
                min="0"
                max="255"
                v-model.number="rgbColor.b"
                @input="updateColorFromRGB"
              />
            </div>
          </div>
        </div>
        
        <!-- 颜色选择器 -->
        <div class="color-picker-section">
          <div class="hue-slider">
            <label>色相</label>
            <input
              type="range"
              min="0"
              max="360"
              v-model.number="hsvColor.h"
              @input="updateColorFromHSV"
              class="hue-range"
            />
          </div>
          <div class="sv-picker">
            <div 
              class="sv-canvas" 
              ref="svCanvas"
              @mousedown="startSVPicker"
              @mousemove="updateSVPicker"
              @mouseup="stopSVPicker"
            >
              <div class="sv-cursor" :style="svCursorStyle"></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 透明度 -->
      <div class="opacity-control" v-if="showOpacity">
        <h4>透明度</h4>
        <div class="opacity-slider">
          <input
            type="range"
            min="0"
            max="100"
            v-model.number="opacity"
            @input="updateOpacity"
          />
          <span class="opacity-value">{{ opacity }}%</span>
        </div>
      </div>

      <!-- 颜色历史 -->
      <div class="color-history" v-if="showHistory && colorHistory.length > 0">
        <h4>最近使用</h4>
        <div class="history-grid">
          <div
            v-for="color in colorHistory"
            :key="color"
            class="color-item standard-color"
            :style="{ backgroundColor: color }"
            @click="selectColor(color)"
          ></div>
        </div>
      </div>
    </div>

    </el-scrollbar>

  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import type { ColorPanelProps, ColorPanelEmits, RGBColor, HSVColor } from './types'
import { ColorUtils } from './utils'

const props = withDefaults(defineProps<ColorPanelProps>(), {
  modelValue: '#000000',
  showOpacity: true,
  showHistory: true,
  maxHistoryCount: 10
})

const emit = defineEmits<ColorPanelEmits>()

const heightContent = computed(() => {
  if (!props.height) {
    return 'height: auto;'
  }
  
  // 处理数字类型，添加 px 单位
  if (typeof props.height === 'number') {
    return `height: ${props.height}px;`
  }
  
  // 处理字符串类型
  return `height: ${props.height};`
})

const widthContent = computed(() => {
  if (!props.width) {
    return 'width: 360px;'
  }
  
  // 处理数字类型，添加 px 单位
  if (typeof props.width === 'number') {
    return `width: ${props.width}px;`
  }
  
  // 处理字符串类型
  return `width: ${props.width};`
})

// 标准颜色（类似Word的标准颜色）
const standardColors = [
  '#000000', '#FFFFFF', '#EEECE1', '#1F497D', '#4F81BD', '#C0504D', '#9BBB59', '#8064A2',
  '#F79646', '#F2F2F2', '#DDD9C3', '#C6D9F0', '#DBE5F1', '#F2DCDB', '#E6E0EC', '#FDE9D9',
  '#D8D8D8', '#BFBFBF', '#95B3D7', '#B8CCE4', '#DCE6F1', '#E1D5E7', '#FCD5B4', '#FAC08F',
  '#C0C0C0', '#A6A6A6', '#8DB4E2', '#9BC2E6', '#C5D9F1', '#D4D4D4', '#E6E6E6', 
]

// 响应式数据
const selectedColor = ref(props.modelValue)
const opacity = ref(100)
const colorHistory = ref<string[]>([])

// RGB颜色对象
const rgbColor = ref<RGBColor>({
  r: 0,
  g: 0,
  b: 0
})

// HSV颜色对象
const hsvColor = ref<HSVColor>({
  h: 0,
  s: 100,
  v: 100
})

// SV选择器相关
const svCanvas = ref<HTMLElement>()
const isDragging = ref(false)

// 计算SV选择器光标位置
const svCursorStyle = computed(() => {
  const s = hsvColor.value.s
  const v = hsvColor.value.v
  return {
    left: `${s}%`,
    top: `${100 - v}%`
  }
})

// 监听颜色变化
watch(() => props.modelValue, (newValue) => {
  selectedColor.value = newValue
  updateRGBFromColor(newValue)
  updateHSVFromRGB()
})

// 从颜色字符串更新RGB
const updateRGBFromColor = (color: string) => {
  const rgb = ColorUtils.parseColor(color)
  if (rgb) {
    rgbColor.value = rgb
  }
}

// 从RGB更新颜色
const updateColorFromRGB = () => {
  const { r, g, b } = rgbColor.value
  selectedColor.value = ColorUtils.rgbToHex(r, g, b)
  updateHSVFromRGB()
}

// 从RGB更新HSV
const updateHSVFromRGB = () => {
  const { r, g, b } = rgbColor.value
  const hsv = ColorUtils.rgbToHsv(r, g, b)
  hsvColor.value = hsv
}

// 从HSV更新颜色
const updateColorFromHSV = () => {
  const { h, s, v } = hsvColor.value
  const rgb = ColorUtils.hsvToRgb(h, s, v)
  rgbColor.value = rgb
  selectedColor.value = ColorUtils.rgbToHex(rgb.r, rgb.g, rgb.b)
  
  // 更新SV选择器的背景颜色
  updateSVPickerBackground()
}

// SV选择器相关方法
const startSVPicker = (event: MouseEvent) => {
  isDragging.value = true
  updateSVPicker(event)
}

const updateSVPicker = (event: MouseEvent) => {
  if (!isDragging.value || !svCanvas.value) return
  
  const rect = svCanvas.value.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top
  
  const s = Math.max(0, Math.min(100, (x / rect.width) * 100))
  const v = Math.max(0, Math.min(100, 100 - (y / rect.height) * 100))
  
  hsvColor.value.s = s
  hsvColor.value.v = v
  updateColorFromHSV()
}

const stopSVPicker = () => {
  isDragging.value = false
}

// 更新SV选择器的背景颜色
const updateSVPickerBackground = () => {
  if (svCanvas.value) {
    const { h } = hsvColor.value
    const hueColor = ColorUtils.hsvToRgb(h, 100, 100)
    const hexColor = ColorUtils.rgbToHex(hueColor.r, hueColor.g, hueColor.b)
    svCanvas.value.style.setProperty('--current-hue-color', hexColor)
  }
}



// 更新透明度
const updateOpacity = () => {
  // 透明度变化时触发事件
  emit('change', getColorWithOpacity())
}

// 获取带透明度的颜色
const getColorWithOpacity = () => {
  if (opacity.value === 100) {
    return selectedColor.value
  }
  const { r, g, b } = rgbColor.value
  return `rgba(${r}, ${g}, ${b}, ${opacity.value / 100})`
}

// 添加到历史记录
const addToHistory = (color: string) => {
  if (!colorHistory.value.includes(color)) {
    colorHistory.value.unshift(color)
    if (colorHistory.value.length > props.maxHistoryCount) {
      colorHistory.value = colorHistory.value.slice(0, props.maxHistoryCount)
    }
  }
}

// 选择颜色时直接确认
const selectColor = (color: string) => {
  selectedColor.value = color
  updateRGBFromColor(color)
  updateHSVFromRGB()
  addToHistory(color)
  
  // 直接触发确认事件
  const finalColor = getColorWithOpacity()
  emit('update:modelValue', finalColor)
  emit('change', finalColor)
  emit('confirm', finalColor)
}

// 初始化
onMounted(() => {
  updateRGBFromColor(props.modelValue)
  updateHSVFromRGB()
  updateSVPickerBackground()
})
</script>

<style scoped>
.color-panel {
  overflow: hidden;
}



.color-panel-content {
  padding: 16px;
}

.color-panel-content h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.standard-colors {
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.standard-colors h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #495057;
  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.8);
}

.custom-color,
.opacity-control,
.color-history {
  margin-bottom: 20px;
}

.standard-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 8px;
  padding: 4px;
}

.color-grid,
.history-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 8px;
}

.color-item {
  width: 28px;
  height: 28px;
  border-radius: 4px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.2s ease;
  position: relative;
  
}

.color-item:hover {
  transform: scale(1.1);
  border-color: #007bff;
}

.color-item.active {
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.3), 0 4px 8px rgba(0, 0, 0, 0.15);
}

.standard-color {
  width: 30px;
  height: 30px;
  box-shadow: 
    0 2px 4px rgba(0, 0, 0, 0.1), 
    0 1px 2px rgba(0, 0, 0, 0.06),
    inset 0 1px 0 rgba(255, 255, 255, 0.2);
  transition: all 0.2s ease;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

.standard-color:hover {
  box-shadow: 
    0 4px 8px rgba(0, 0, 0, 0.15), 
    0 2px 4px rgba(0, 0, 0, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.3);
  transform: translateY(-1px);
  border-color: rgba(0, 0, 0, 0.2);
}

.standard-color.active {
  box-shadow: 
    0 0 0 2px rgba(0, 123, 255, 0.5),
    0 4px 8px rgba(0, 0, 0, 0.15), 
    0 2px 4px rgba(0, 0, 0, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.4);
  transform: translateY(-1px);
  border-color: #007bff;
}

.color-picker-container {
  display: flex;
  gap: 16px;
  align-items: flex-start;
  margin-bottom: 16px;
}

.color-preview {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  border: 2px solid #e0e0e0;
  flex-shrink: 0;
}

.color-inputs {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.input-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.input-group label {
  font-size: 12px;
  font-weight: 600;
  color: #666;
  min-width: 16px;
}

.input-group input {
  width: 60px;
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 12px;
  text-align: center;
}

.input-group input:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.2);
}

/* 颜色选择器样式 */
.color-picker-section {
  margin-top: 16px;
}

.hue-slider {
  margin-bottom: 12px;
}

.hue-slider label {
  display: block;
  font-size: 12px;
  font-weight: 600;
  color: #666;
  margin-bottom: 6px;
}

.hue-range {
  width: 100%;
  height: 8px;
  border-radius: 4px;
  background: linear-gradient(to right, 
    #ff0000 0%, #ffff00 17%, #00ff00 33%, 
    #00ffff 50%, #0000ff 67%, #ff00ff 83%, #ff0000 100%);
  outline: none;
  -webkit-appearance: none;
}

.hue-range::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: white;
  border: 2px solid #007bff;
  cursor: pointer;
}

.hue-range::-moz-range-thumb {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: white;
  border: 2px solid #007bff;
  cursor: pointer;
}

.sv-picker {
  position: relative;
  width: 100%;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  border: 2px solid #e0e0e0;
}

.sv-canvas {
  width: 100%;
  height: 100%;
  cursor: crosshair;
  position: relative;
  background: linear-gradient(to top, #000, transparent), 
              linear-gradient(to right, #fff, var(--current-hue-color));
}

.sv-cursor {
  position: absolute;
  width: 12px;
  height: 12px;
  border: 2px solid white;
  border-radius: 50%;
  pointer-events: none;
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.5);
  transform: translate(-50%, -50%);
}

.opacity-slider {
  display: flex;
  align-items: center;
  gap: 12px;
}

.opacity-slider input[type="range"] {
  flex: 1;
  height: 4px;
  border-radius: 2px;
  background: #e0e0e0;
  outline: none;
  -webkit-appearance: none;
}

.opacity-slider input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: #007bff;
  cursor: pointer;
}

.opacity-slider input[type="range"]::-moz-range-thumb {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: #007bff;
  cursor: pointer;
  border: none;
}

.opacity-value {
  font-size: 12px;
  color: #666;
  min-width: 40px;
  text-align: right;
}



/* 响应式设计 */
@media (max-width: 480px) {
  .color-panel {
    max-width: 360px;
  }
  
  .standard-grid {
    grid-template-columns: repeat(6, 1fr);
  }
  
  .color-grid,
  .history-grid {
    grid-template-columns: repeat(6, 1fr);
  }
  
  .color-picker-container {
    flex-direction: column;
    gap: 12px;
  }
  
  .color-preview {
    width: 100%;
    height: 40px;
  }
}
</style>
